package com.hg.util.common;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.junit.Test;

import com.hg.util.weixin.MD5Util;

public class Common
{
	/**
	 * 获取应用路径
	 * http://base.huibaoming.com/haihsc/weixin/user/do_login.do?id=2&pid=3中的
	 * /weixin/user/do_login.do?id=2&pid=3
	 * 
	 * @param app_name		指的是:haihsc,如果为null,则使用当前项目位置
	 * @param route_name	指的是:weixin/user  ,如果为null,则默认没有
	 * @param param			指的是把参数放到map集合中
	 * @return
	 */
	public static String app_url(String app_name,String route_name,Map<String ,String> param){
		String url ="";
		if(null==app_name){
			
		}
		
		return null;
	}
	
	/**
	 * 获取项目路径  比如: http://base.huibaoming.com/haihsc
	 * @param request
	 * @return
	 */
	public static String getProjectUrl(HttpServletRequest request){
		
		return request.getScheme() + "://" + request.getServerName()+request.getContextPath();
	}
	
	/**
	 * 获取当前是数字化的星期几  比如: 星期一 = 1 ，星期二 = 2.。。
	 * @param request
	 * @return
	 */
	public static int getWeekDay()
	{
		Date date = new Date();
		SimpleDateFormat dateFm = new SimpleDateFormat("EEEE");
		String s = dateFm.format(date);
		System.out.println("现在是 ： "+s);
		if("星期一".equals(s)){
			return 1;
		}else if("星期二".equals(s)){
			return 2;
		}else if("星期三".equals(s)){
			return 3;
		}else if("星期四".equals(s)){
			return 4;
		}else if("星期五".equals(s)){
			return 5;
		}else if("星期六".equals(s)){
			return 6;
		}else{
			return 0;
		}
	}

	public static int dayToNum(String s){
		if("一".equals(s)){
			return 1;
		}else if("二".equals(s)){
			return 2;
		}else if("三".equals(s)){
			return 3;
		}else if("四".equals(s)){
			return 4;
		}else if("五".equals(s)){
			return 5;
		}else if("六".equals(s)){
			return 6;
		}else{
			return 0;
		}
	}
	
	@Test
	public void test_1(){
		System.out.println(dayToNum("星期六"));
	}
	
	
	/**
	 * 获取当前项目的域名  比如: http://base.huibaoming.com
	 * @param request
	 * @return
	 */
	public static String getSite_domain(HttpServletRequest request){
		return request.getScheme() + "://" + request.getServerName();
	}
	
	/**
	 * 获得客户端的ip地址 120.11.11.11
	 * @param request
	 * @return
	 */
	public static String getRemoteAddr(HttpServletRequest request){
		return request.getRemoteAddr();
	}
	
	/**
	 * 是获得客户端的主机名
	 * @param request
	 * @return
	 */
	public static String getRemoteHost(HttpServletRequest request){
		return request.getRemoteHost();
	}
	
	/**
	 * URL转码
	 * 特殊字符处理
	 * 如果不支持改字符编码,则不进行字符编码
	 * @param src
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String UrlEncode(String src){
		try
		{
			return URLEncoder.encode(src, "UTF-8").replace("+", "%20");
		}
		catch (UnsupportedEncodingException e)
		{
			//e.printStackTrace();
			return src;
		}
	}
	
	/**
	 * 201610311925259473
	 * 获取当前时间的字符串
	 * @return
	 */
	public static String createNotice_sn(){
		Random random = new Random();
		int num =1000+ random.nextInt(9000);
		
		Date now = new Date(); 
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");//可以方便地修改日期格式
		return dateFormat.format(now)+num;
	}
	
	
	/**
	 * 获取32随机字符串
	 * @return
	 */
	public static String createNoncestr() {
		Random random = new Random();
		return MD5Util.MD5Encode(String.valueOf(random.nextInt(10000)), "UTF-8");
	}
	/**
	 * 获取硬盘根目录  例如：/E:/MyEclipse2014/Workspaces/haihsc/WebRoot/WEB-INF/classes/
	 * 
	 * @return
	 */
	public static String getCurrentPath(){  
	       //取得根目录路径  
		String rootPath=Thread.currentThread().getContextClassLoader().getResource("").getPath();
	    return rootPath;         
	}
	
	/**
	 * 获取时间戳整数
	 * @return
	 */
	public static int getTimeStamp() {
		long time_long = System.currentTimeMillis() / 1000;
		int time = (int) time_long;
		return time;
	}
	/**
	 * 获取时间戳字符串
	 * @return
	 */
	public static String getTimeStampStr() {
		
		return getTimeStamp()+"";
	}
	
	/**
	 * 把字符串首字母转换为大写
	 * @param str
	 * @return
	 */
	public static String UpStr(String str)
	{
		return str.replaceFirst(str.substring(0, 1),str.substring(0, 1).toUpperCase()) ;
	}
	
	/**
	 * 把字符串首字母转换为小写
	 * @param str
	 * @return
	 */
	public static String downStr(String str)
	{
		return str.replaceFirst(str.substring(0, 1),str.substring(0, 1).toLowerCase()) ;
	}
	
	/**
	 * 将时间戳转换为字符串
	 * @param timeStamp
	 * @return
	 */
	public static String TimeStampToString(long timeStamp,String fromat){
		long time_long = timeStamp*1000;
		SimpleDateFormat sdf = new SimpleDateFormat(fromat);
		Date date = new Date(time_long);
		return sdf.format(date);
	}
	
	/**
	 * 将时间戳转换为字符串，默认格式yyyyMMdd HH:mm:ss
	 * @param timeStamp
	 * @return
	 */
	public static String TimeStampToString(long timeStamp){
		return TimeStampToString(timeStamp,"yyyyMMdd HH:mm:ss");
	}
	
	/**
	 * 默认返回当前时间戳的字符串
	 * @return
	 */
	public static String TimeStampToString(){
		return TimeStampToString(getTimeStamp());
	}
	
	/**
	 * 将字符串转换为时间戳
	 * @param date
	 * @return
	 * @throws ParseException 
	 */
	public static int StringToTimeStamp(String time,String format){
		try{
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			Date date = null;
			date = sdf.parse(time); 
			long time_long = date.getTime()/1000;
			int time_int = (int)time_long;
			return time_int;
		}catch(Exception e){
			e.printStackTrace();
			return 0;
		}
	}
	

	 /* 读取json文件
	 * @Path Path   文件路径
	 * @return 返回json
	 */
	public static String ReadFile(String Path){
		BufferedReader reader = null;
		String jsonstr = "";
		try{
			FileInputStream fileInputStream = new FileInputStream(Path);
			InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
			reader = new BufferedReader(inputStreamReader);
			String tempString = null;
			while((tempString = reader.readLine()) != null){
				jsonstr += tempString;
			}
			reader.close();
		}catch(IOException e){
			e.printStackTrace();
		}finally{
			if(reader != null){
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return jsonstr;
	}
	
	/**
	 * 
	 * @param packageParams
	 * @param urlencode
	 * @return kon=23&kong=123&
	 */
	public static String formatQueryParaMap(Map<String, String> packageParams,boolean urlencode){
		StringBuffer sb = new StringBuffer();
		Set es = packageParams.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k)
					&& !"key".equals(k)) {
				if(urlencode){
					v=UrlEncode(v);
				}
				sb.append(k + "=" + v + "&");
			}
		}
		return sb.toString();
	}
	
	//该类进行处理参数为空和为字符串的问题
	public static boolean checkParam(String ... params){
		int i=1;
		for(String param : params){
			if(param == null || param.trim().equals("")){
				i++;
				return false;
			}
		}
		return true;
	}
	
	/**
	 * 前端地址存储到数据库时需要
	 * @param url
	 * @return
	 */
	public static String formatFileUrlFromVoToDto(String url){
		if(url.startsWith("http:")){
			return url;
		}else if(-1!=url.indexOf("public/")){
			return "./"+url.substring(url.indexOf("public/"));
		}else{
			return "";
		}
	}
	
	/**
	 * 从数据库中读取出地址时需要
	 * @param url
	 * @return
	 */
	public static String formatFileUrlFromDtoToVo(String url){
		if(url.startsWith("http:")){
			return url;
		}else if(-1!=url.indexOf("public/")){
			return url.replace("./","");
		}else{
			return "";
		}
	}
	
	/**
	 * 用于解决中文乱码的工具类
	 * @param data
	 * @return
	 */
	public static String changeData(String data) {
		try
		{
			if(data == null){
				System.out.println("data in is "+data);
				return null;
			}
			byte[] source = data.getBytes("ISO8859-1");
			data = new String(source, "UTF-8");
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return data;
	}
	
	/**
	 * 获取日期所处的number  0,1,2,3,4,5,6
	 * @param dt
	 * @return
	 */
	public static int getWeekOfNum(Date dt){
		Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0){
        	w = 0;
        }
        
        return w;
	}
	
	public static int getWeekOfNum(){
		Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0){
        	w = 0;
        }
        
        return w;
	}
	
	/**
     * 获取当前日期是星期几<br>
     * 
     * @param dt
     * @return 当前日期是星期几
     */
	public static String getWeekOfDate(Date dt) {
		String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
		
		return weekDays[getWeekOfNum(dt)];
	}
	
	public static String getWeekOfDate(int num) {
		String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
		
		return weekDays[num];
	}
	
	public static String getWeekOfDate() {
		
		return getWeekOfDate(new Date());
	}
	public static String getExceptionAllinformation(Exception ex){
        String sOut = "";
        StackTraceElement[] trace = ex.getStackTrace();
        for (StackTraceElement s : trace) {
            sOut += "\tat " + s + "\r\n";
        }
        return sOut;
	}
	
	
	
	/***
	 * 
	 * 将整数时间23:00转成2300
	 * 
	 * 例子:System.out.println(StringNumbersTime("23:00",":"));
	 * 
	 * @param time			23:00
	 * @param format		格式如     :    23:00
	 * @return
	 */
	public static int StringNumbersTime(String time,String format){
		return Integer.parseInt(time.replace(format,""));//TODO 获取当前时间并去掉:
	}
	
	/**
	 * 
	 * 时间相加
	 * 
	 * @param time  时间
	 * @return
	 */
	public static int TimeAddition(int time){
		int minute=60;//TODO 分钟
		int num_time=time/100+minute/100;//TODO 时间相加
		
		int num_fen=minute%100+time%100;//TODO 时间取余
		
		return num_time*100+(num_fen/60)*100+(num_fen%60)-100;
		
	}
	
	/**
	 * 把 1802转化成18:02
	 * @param time
	 * @return
	 */
	public static String getTimeStr(int time){
		if(time>99){
			int num =time%100;
			if(num>9){
				return (int)time/100+":"+num;
			}else{
				return (int)time/100+":0"+num;
			}
		}else if(time>0){
			return "0:"+time;
		}else{
			return "输入的时间格式不对";
		}
	}
}
